<template>
    <div>
      <el-row>
        <el-col :span="24">
          <el-card>
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="收费策略编号">
                <el-input v-model="formInline.code"></el-input>
              </el-form-item>
              <el-form-item label="收费策略描述">
                <el-input v-model="formInline.description"></el-input>
              </el-form-item>
              <el-form-item label="会员折扣比例">
                <el-input v-model="formInline.memberDiscount"></el-input>
              </el-form-item>
              <el-form-item label="每小时费率">
                <el-input v-model="formInline.hourlyRate"></el-input>
              </el-form-item>
              <el-form-item label="是否启用">
                <el-select v-model="formInline.isAvailable" style="width: 200px;" placeholder="请选择">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-config-provider :locale="locale">
                  <el-date-picker
                    v-model="formInline.createTime"
                    type="date"
                    placeholder="选择日期时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :locale="locale"
                  />
                </el-config-provider>
              </el-form-item>
              <el-form-item label="修改时间">
                <el-config-provider :locale="locale">
                  <el-date-picker
                    v-model="formInline.updateTime"
                    type="date"
                    placeholder="选择日期时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :locale="locale"
                  />
                </el-config-provider>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="fetchData">查询</el-button>
                <el-button type="info" @click="resetQueryData">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-card v-loading="isLoading" element-loading-text="加载中...">
            <el-form-item style="float: right;">
                <el-button type="success" @click="showAddDialog = true">新增</el-button>
                <el-button type="warning" @click="handleBatchDelete" >批量删除</el-button>
                <el-button type="danger" @click="deleteAll" >清空数据</el-button>
              </el-form-item>
            <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="序号" width="70" align="center" style = "background-color :black">
                <template #default="scope">
                  <div class="serial-number">
                    {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="id" label="收费策略id" v-if="false"></el-table-column>
              <el-table-column prop="code" label="收费策略编号" width="130"></el-table-column>
              <el-table-column prop="memberDiscount" label="会员折扣比例" width="130"></el-table-column>
              <el-table-column prop="hourlyRate" label="每小时费率(元/时)" width="130"></el-table-column>
              <el-table-column prop="isAvailable" label="是否启用" width="130">
                <template #default="scope">
                  <span>{{ scope.row.isAvailable === 1 ? '是' : '否' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="收费策略描述" width="500"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
              <el-table-column prop="updateTime" label="修改时间" width="180"></el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
                  <el-button size="small" type="danger" @click="handleDelete([scope.row.id])">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
              <el-config-provider :locale="locale">
                <el-pagination
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                ></el-pagination>
              </el-config-provider>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 引入新增停车场对话框组件 -->
      <AddFeeScheduleDialog 
        :visible="showAddDialog" 
        @update:visible="showAddDialog = $event"
        @add="handleAdd"
      />
      <EditFeeScheduleDialog 
        :visible="showEditDialog" 
        :feeScheduleId="updateFeeScheduleId"
        :updateCode="updateCode"
        :updateDescription="updateDescription"
        :updateMemberDiscount="updateMemberDiscount"
        :updateHourlyRate="updateHourlyRate"
        :updateIsAvailable="updateIsAvailable"
        @update:visible="showEditDialog = $event"
        @edit="fetchData"
      />
    </div>
  </template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, watch } from 'vue';
import axios from 'axios';
import AddFeeScheduleDialog from '@/components/AddFeeScheduleDialog.vue';
import EditFeeScheduleDialog from '@/components/EditFeeScheduleDialog.vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const route = useRoute();
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const updateFeeScheduleId = ref(0);
const updateCode = ref('');
const updateDescription= ref('');
const updateMemberDiscount= ref('');
const updateHourlyRate= ref('');
const updateIsAvailable= ref('');

// 初始化查询条件对象
const formInline = ref({
  id: '',
  code: '',
  description: '',
  hourlyRate: '',
  memberDiscount: '',
  isAvailable: '',
  createTime: null,
  updateTime: null
});
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const locale = zhCn;
const isLoading = ref(false);
const selectedIds = ref([]);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})

// 监听路由变化, 避免在其他页面修改影响本页面数据时不自动刷新的情况
watch(() => route.path, (newPath) => {
  if(newPath === '/admin/FeeScheduleManagement') {
    console.error("刷新FeeScheduleManagement");
    fetchData();
  }
});
// 获取数据函数
const fetchData = async () => {
  isLoading.value = true;
  const params = {
      ...formInline.value,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  if ('code' in params && params.code) {
    params.feeScheduleCode = params.code;
    delete params.code;
  }
  try {
    const response = await api.get('/api/v1/fee-schedule/fee-schedule-info', { params });
    if (response.data.code === "200") {
        if(response.data.data != null){
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      } else {
        ElMessage({
          title: '错误',
          message: '获取收费策略记录失败！' + response.data.message,
          type: 'error',
          showClose: false
        });
      }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取收费策略记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};
// 新增按钮点击事件处理
const handleAdd = async () => {
  await fetchData();
};
// 编辑和删除事件处理保持不变
const handleEdit = async (row) => {
  updateFeeScheduleId.value = row.id;
  updateCode.value = row.code;
  updateDescription.value = row.description;
  updateMemberDiscount.value = row.memberDiscount;
  updateHourlyRate.value = row.hourlyRate;
  updateIsAvailable.value = row.isAvailable;
  showEditDialog.value = true;
};
const handleDelete = async (ids) => {
  try {
    const response = await api.delete('/api/v1/fee-schedule/fee-schedule-info', {
        data: { ids }
    });
    if (response.data.code === "200") {
      ElMessage({
        title: '成功',
        message: '删除成功',
        type: 'success',
        showClose: false
      });
      // 清空已选择的ID列表
      selectedIds.value = [];
    } else {
      ElMessage({
        title: '错误',
        message: '删除失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '删除失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    await fetchData();
    isLoading.value = false;
  }
};
const handleBatchDelete = async () => {
  handleDelete(selectedIds.value);
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};
// 分页事件处理
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};
// 每页显示条数改变时触发
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};
const deleteAll = async () => {
  ElMessageBox.confirm(
    '此操作将永久删除所有数据, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    isLoading.value = true; // 开始加载
    try {
      // 发送删除请求到后端
      const response = await api.delete('/api/v1/fee-schedule/all-fee-schedule-info');
      if (response.data.code === "200") {
        ElMessage({
          title: '成功',
          message: '所有数据删除成功',
          type: 'success',
          showClose: false,
        });
        // 清空前端 tableData
        tableData.value = [];
      } else {
        ElMessage({
          title: '错误',
          message: '删除失败！' + response.data.message,
          type: 'error',
        });
      }
    } catch (error) {
      ElMessage({
        title: '错误',
        message: '删除失败！' + error.message,
        type: 'error',
      });
    } finally {
      isLoading.value = false;
      fetchData();
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
const resetQueryData = () =>{
  formInline.value = {
    id: '',
    code: '',
    description: '',
    hourlyRate: '',
    memberDiscount: '',
    isAvailable: '',
    createTime: null,
    updateTime: null
  };
  fetchData();
}

// 页面加载时自动获取数据
fetchData();
</script>
  
  <style scoped>
  .admin-dashboard {
    height: 100vh;
  }
  .el-container {
    height: 100%;
  }
  .el-aside {
    background-color: #f8f9fa;
  }
  .el-main {
    padding: 20px;
  }
  .el-card {
    margin-bottom: 20px;
  }
  /* 确保鼠标悬停时的交互效果不变 */
  .el-table .cell {
    pointer-events: none;
  }
</style>